import {
  Body,
  Controller,
  HttpStatus,
  HttpCode,
  UsePipes,
  Post,
  Put,
  Delete,
  HttpException,
  UseInterceptors,
  UseFilters,
} from '@nestjs/common';
import { classToPlain } from 'class-transformer';
import { IdDto } from 'src/common/dto/id.dto';
import { DtoPipe } from '../common/pipe/dto.pipe';
import { EmployeeEntity } from './employee.entity';
import { EmployeeService } from './employee.service';
import { EmployeeSearchDto } from './dto/employee.search.dto';
import { EmployeeInsertDto } from './dto/employee.insert.dto';
import { EmployeeUpdateDto } from './dto/employee.update.dto';
import { EmployeeSignDto } from './dto/employee.sign.dto';
import { ResultApiInterceptor } from 'src/common/interceptor/result.api.interceptor';
import { ErrorFilter } from 'src/common/filter/error.filter';

@Controller('/api/employee')
export class EmployeeController {
  constructor(private readonly employeeService: EmployeeService) {}

  // 获取列表
  @Post('/list')
  @UsePipes(DtoPipe)
  @HttpCode(HttpStatus.OK)
  async get(@Body() bodys: EmployeeSearchDto): Promise<any> {
    const searchParam = new EmployeeSearchDto();
    const param = Object.assign(searchParam, bodys);
    const list: EmployeeEntity[] =
      await this.employeeService.getManyAndCount(param);
    return classToPlain(list);
  }

  /**
   * 根据id查询用户
   * @param Param 用户id
   * @function classToPlain 表示使用class-transformer内置方法返回数据（eg：可能涉及到排除某个字段，在entity中使用@Exclude()进行排除）
   */
  @Post('/id')
  @HttpCode(HttpStatus.OK)
  async findOne(@Body() body: IdDto): Promise<any> {
    const findOneById: EmployeeEntity = await this.employeeService.findOneById(
      body.id,
    );
    return classToPlain(findOneById); // 使用nestjs自带的序列化返回值成功
  }

  // 新增
  @Post('/add')
  @UsePipes(DtoPipe)
  @HttpCode(HttpStatus.OK)
  async add(@Body() body: EmployeeInsertDto): Promise<boolean> {
    const data: boolean = await this.employeeService.save(body);
    return data;
  }

  // 编辑
  @Put('/edit')
  @UsePipes(DtoPipe)
  @HttpCode(HttpStatus.OK)
  async edit(@Body() body: EmployeeUpdateDto): Promise<any> {
    return await this.employeeService.updateById(body);
  }

  // 删除
  @Delete('/delete')
  @UsePipes(DtoPipe)
  @HttpCode(HttpStatus.OK)
  async delete(@Body() request: IdDto): Promise<any> {
    return await this.employeeService.deleteById(request);
  }

  // 登陆
  @Post('sign_in')
  @UsePipes(DtoPipe)
  @UseFilters(ErrorFilter)
  @UseInterceptors(ResultApiInterceptor)
  @HttpCode(HttpStatus.OK)
  async signIn(@Body() body: EmployeeSignDto): Promise<any> {
    try {
      return await this.employeeService.login(body);
    } catch (error) {
      throw new HttpException({ message: error.response }, error.status);
    }
  }

  // 注册
  @Post('sign_up')
  @UsePipes(DtoPipe)
  @UseInterceptors(ResultApiInterceptor)
  @HttpCode(HttpStatus.OK)
  async signUp(@Body() body: EmployeeSignDto): Promise<boolean> {
    return await this.employeeService.register(body);
  }
}
